<template>
  <div class="user-reading-analysis">
    <template v-if="loading">
      <div class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
    </template>

    <template v-else-if="analysisData">
      <div class="analysis-content">
        <!-- 阅读统计卡片 -->
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-view"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value highlight-text">{{ analysisData.totalViews || 0 }}</div>
              <div class="stat-label">总阅读数</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-timer"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value highlight-text">{{ timeAnalysis.totalReadMinutes || 0 }}</div>
              <div class="stat-label">总阅读分钟</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-alarm-clock"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value highlight-text">{{ timeAnalysis.avgReadMinutes || 0 }}</div>
              <div class="stat-label">平均阅读分钟/篇</div>
            </div>
          </div>
        </div>
        
        <!-- 标签分布 -->
        <div v-if="analysisData.favoriteTags && analysisData.favoriteTags.length > 0" class="analysis-section">
          <h4 class="section-title">您感兴趣的标签</h4>
          <div class="tags-distribution">
            <div 
              v-for="tag in analysisData.favoriteTags.slice(0, 5)" 
              :key="tag.id" 
              class="tag-item"
              :style="{fontSize: calculateTagSize(tag.count) + 'px'}"
            >
              {{ tag.name }} <span class="highlight-text small">{{ tag.count }}</span>
            </div>
          </div>
        </div>
        
        <!-- 分类分布 -->
        <div v-if="analysisData.categoryStats && analysisData.categoryStats.length > 0" class="analysis-section">
          <h4 class="section-title">阅读分类分布</h4>
          <div class="category-distribution">
            <div 
              v-for="category in analysisData.categoryStats" 
              :key="category.id" 
              class="category-bar"
            >
              <div class="category-name">
                {{ category.name }}
                <span class="highlight-text small">{{ category.count }} 篇</span>
              </div>
              <div class="bar-container">
                <div 
                  class="bar-fill" 
                  :style="{
                    width: calculateCategoryPercentage(category.count) + '%',
                    backgroundColor: getRandomColor(category.id)
                  }"
                ></div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 阅读趋势 -->
        <div v-if="analysisData.readingTrends && analysisData.readingTrends.length > 0" class="analysis-section">
          <h4 class="section-title">阅读趋势</h4>
          <div class="reading-trends">
            <div class="line-chart">
              <!-- 折线图点 -->
              <div class="line-points">
                <div 
                  v-for="(trend, index) in analysisData.readingTrends" 
                  :key="index"
                  class="chart-column"
                >
                  <div 
                    class="data-point" 
                    :style="{
                      bottom: calculateTrendHeight(trend.count) + '%'
                    }"
                  >
                    <div class="point-tooltip">{{ trend.count }} 篇</div>
                  </div>
                  <div class="date-label">{{ formatShortDate(trend.date) }}</div>
                </div>
              </div>
              
              <!-- 折线 SVG -->
              <svg class="trend-line" :viewBox="`0 0 ${(analysisData.readingTrends.length - 1) * 100} 100`" preserveAspectRatio="none">
                <polyline
                  :points="getLinePoints()"
                  fill="none"
                  stroke="var(--primary, #409EFF)"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
                <path
                  :d="`${getLinePoints(true)} V 100 H 0 Z`"
                  fill="var(--primary, #409EFF)"
                  fill-opacity="0.1"
                />
              </svg>
            </div>
          </div>
        </div>
      </div>
    </template>

    <template v-else-if="error">
      <div class="error-container">
        <el-alert
          title="获取数据失败"
          type="error"
          :description="error"
          show-icon
        />
      </div>
    </template>

    <template v-else>
      <div class="no-data">
        <el-empty description="暂无阅读数据" :image-size="80"></el-empty>
      </div>
    </template>
  </div>
</template>

<script>
import { getUserBrowsingAnalysisApi } from '@/api/recommendation';
import { formatDate } from '@/utils/date';

export default {
  name: 'UserReadingAnalysis',
  data() {
    return {
      loading: false,
      analysisData: null,
      error: null
    };
  },
  computed: {
    timeAnalysis() {
      return this.analysisData && this.analysisData.timeAnalysis || {};
    }
  },
  methods: {
    formatDate,
    formatShortDate(dateStr) {
      const date = new Date(dateStr);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    fetchAnalysisData() {
      this.loading = true;
      this.error = null;
      
      getUserBrowsingAnalysisApi()
        .then(res => {
          if (res.code === 200 && res.data) {
            this.analysisData = res.data;
          } else {
            this.error = res.message || '获取数据失败';
          }
        })
        .catch(error => {
          console.error('获取阅读统计分析失败:', error);
          this.error = '获取阅读统计分析失败';
        })
        .finally(() => {
          this.loading = false;
        });
    },
    calculateTagSize(count) {
      // 根据标签使用量计算字体大小，范围在12-22之间
      const maxCount = Math.max(...(this.analysisData.favoriteTags || []).map(t => t.count));
      if (maxCount <= 0) return 14;
      return 12 + (count / maxCount) * 10;
    },
    calculateCategoryPercentage(count) {
      // 计算分类在图表中的百分比宽度
      const maxCount = Math.max(...(this.analysisData.categoryStats || []).map(c => c.count));
      if (maxCount <= 0) return 5;
      return 5 + (count / maxCount) * 95;
    },
    calculateTrendHeight(count) {
      // 计算趋势图中柱状图的高度百分比
      const maxCount = Math.max(...(this.analysisData.readingTrends || []).map(t => t.count));
      if (maxCount <= 0) return 5;
      return 5 + (count / maxCount) * 95;
    },
    getRandomColor(id) {
      // 根据ID生成固定的颜色，保证同一分类始终是同一颜色
      const colors = [
        '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
        '#626aef', '#6f7ad3', '#1989fa', '#5cb87a', '#ff9f7f'
      ];
      return colors[id % colors.length];
    },
    getTrendColor(count) {
      // 根据阅读量生成渐变色
      const maxCount = Math.max(...(this.analysisData.readingTrends || []).map(t => t.count));
      if (maxCount <= 1) return '#409EFF';
      
      const ratio = count / maxCount;
      if (ratio > 0.8) return '#F56C6C'; // 高热度
      if (ratio > 0.5) return '#E6A23C'; // 中等热度
      if (ratio > 0.3) return '#67C23A'; // 较低热度
      return '#909399'; // 低热度
    },
    getLinePoints(forPath = false) {
      // 生成折线图的点坐标
      if (!this.analysisData || !this.analysisData.readingTrends || this.analysisData.readingTrends.length === 0) {
        return '';
      }
      
      const trends = [...this.analysisData.readingTrends].reverse(); // 反转数组以时间正序显示
      const maxCount = Math.max(...trends.map(t => t.count));
      if (maxCount <= 0) return '';
      
      // 计算每个点的坐标
      let points = trends.map((trend, index) => {
        const x = index * 100; // SVG viewBox 中的 x 坐标
        let y = 100 - (trend.count / maxCount * 90);
        if (y > 95) y = 95; // 确保至少有一点高度
        if (y < 5) y = 5;  // 确保不会超出顶部
        return `${x},${y}`;
      }).join(' ');
      
      if (forPath) {
        return `M ${points}`;
      }
      return points;
    }
  },
  created() {
    this.fetchAnalysisData();
  }
};
</script>

<style lang="scss" scoped>
.user-reading-analysis {
  margin-top: 32px;
}

.loading-container, .no-data, .error-container {
  padding: 16px;
  display: flex;
  justify-content: center;
}

// 高亮文字样式
.highlight-text {
  color: var(--primary, #409EFF);
  font-weight: 700;
  
  &.small {
    font-size: 0.85rem;
    font-weight: 600;
  }
}

// 统计卡片样式
.stat-cards {
  display: flex;
  gap: 24px;
  margin-bottom: 36px;
  flex-wrap: wrap;
  
  @media (max-width: 640px) {
    flex-direction: column;
    gap: 16px;
  }
}

.stat-card {
  flex: 1;
  min-width: 120px;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  
  .stat-icon {
    font-size: 2.2rem;
    margin-right: 16px;
    color: var(--primary);
    opacity: 0.8;
  }
  
  .stat-info {
    .stat-value {
      font-size: 1.8rem;
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 0.9rem;
      color: var(--text-secondary);
    }
  }
}

// 分析区域通用样式
.analysis-section {
  margin-bottom: 40px;
  padding-top: 20px;
  
  .section-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 20px;
    color: var(--text-primary);
    position: relative;
    padding-bottom: 12px;
    
    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 40px;
      height: 3px;
      background-color: var(--primary);
      border-radius: 3px;
    }
  }
}

// 标签分布样式
.tags-distribution {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  
  .tag-item {
    padding: 8px 16px;
    background-color: rgba(0, 0, 0, 0.02);
    border-radius: 20px;
    color: var(--text-primary);
    cursor: pointer;
    transition: all 0.3s;
    border: 1px solid rgba(0, 0, 0, 0.04);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      background-color: #fff;
    }
  }
}

// 分类分布样式
.category-distribution {
  .category-bar {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .category-name {
      font-size: 1rem;
      margin-bottom: 8px;
      color: var(--text-primary);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .bar-container {
      height: 12px;
      background-color: rgba(0, 0, 0, 0.03);
      border-radius: 6px;
      position: relative;
      overflow: hidden;
      
      .bar-fill {
        height: 100%;
        background-color: var(--primary);
        border-radius: 6px;
        transition: width 1s cubic-bezier(0.23, 1, 0.32, 1);
      }
    }
  }
}

// 阅读趋势样式
.reading-trends {
  margin-top: 16px;
  
  .line-chart {
    position: relative;
    height: 200px;
    width: 100%;
    
    .line-points {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 30px;
      display: flex;
      justify-content: space-between;
      z-index: 2;
      
      .chart-column {
        flex: 1;
        position: relative;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .data-point {
          position: absolute;
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background-color: #fff;
          border: 2px solid var(--primary);
          z-index: 3;
          transition: all 0.3s ease;
          cursor: pointer;
          
          .point-tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%) translateY(-8px);
            background-color: var(--primary);
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            white-space: nowrap;
            opacity: 0;
            transition: all 0.2s ease;
            pointer-events: none;
            font-weight: 500;
            margin-bottom: 3px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
            
            &:after {
              content: '';
              position: absolute;
              top: 100%;
              left: 50%;
              margin-left: -4px;
              border-width: 4px;
              border-style: solid;
              border-color: var(--primary) transparent transparent transparent;
            }
          }
          
          &:hover {
            transform: scale(1.2);
            box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2);
            
            .point-tooltip {
              opacity: 1;
              transform: translateX(-50%) translateY(-4px);
            }
          }
        }
        
        .date-label {
          position: absolute;
          bottom: -25px;
          left: 50%;
          transform: translateX(-50%);
          font-size: 0.85rem;
          color: var(--text-secondary);
          white-space: nowrap;
        }
      }
    }
    
    .trend-line {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: calc(100% - 30px);
      z-index: 1;
    }
  }
}
</style> 